﻿using System;
using System.Collections.Generic;
using System.Xml.Schema;
using Account;
using Smart.Model;
using UnityEngine;

public class MainPlayer : Player
{
    private Vector3 moveDir;
    private float moveLen;
    private bool moveDirChanged;
    private readonly long SyncDistance = (long)(0.1f * 65536f);
    public override void OnCreate()
    {
        base.OnCreate();

        CameraController.instance.target = transform;
        CameraController.instance.UpdatePos();

        Joystick.instance.EventDown = OnMove;
        Joystick.instance.EventMove = OnMove;
        Joystick.instance.EventUp = OnStop;
    }

    private void OnStop()
    {
        RaceStopMove();
        Net.MoveStopReqMessage();
    }

    private void OnMove(Vector3 dir, float len)
    {
        // if (dir.x == moveDir.x && dir.y == moveDir.y) return;
        moveDirChanged = true; 
        moveDir = dir;
        moveLen = len;
    }

    public override void Update()
    {
        ProcssInput();
        UpdatePostion();
        base.Update();
    }

    private void ProcssInput()
    {
        if (!moveDirChanged) return;
        moveDirChanged = false;

        RaceGetPos(out var xx, out var yy, out var zz);

        var v = transform.parent.worldToLocalMatrix.MultiplyVector(transform.localToWorldMatrix.MultiplyVector(new Vector3(moveDir.x, 0, moveDir.y)));
        RaceLogic.ClientPosToRace(v.x, v.y, v.z, out var x, out var y, out var z);
        Net.MoveReqMessage(x, z, xx, yy, zz);
        Debug.Log($"MoveReqMessage (localX:{moveDir.x} localZ:{moveDir.y}) (clientX:{v.x} clientZ:{v.z}) (serverX:{x} Z:{z})");

        RaceMoveVelocity(x, 0, z);
    }

    private void UpdatePostion()
    {
        RaceGetPosClient(out var x, out var y, out var z);
        transform.position = new Vector3(x, y + 0.9f, z);
        Debug.Log(transform.position);
    }

    public void SyncPosition(long x, long y, long z)
    {
        RaceGetPos(out var xx, out var yy, out var zz);
        
        if(Math.Pow(xx - x, 2) + Math.Pow(xx - x, 2) + Math.Pow(xx - x, 2) > SyncDistance)
        {
            ResetPosition(x, y, z);
        }
    }

    public void ResetPosition(long x, long y, long z)
    {
        SetByRacePosition(x, y, z);
    }

    public override void OnDestroy()
    {
        if(Joystick.instance) Joystick.instance.EventMove = null;
        if (CameraController.instance) CameraController.instance.target = null;
        base.OnDestroy();
    }

}